package utils;

/**
 * @author xbl
 * @date 2018/9/12 22:52
 */

import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

public class DownUtil {
    //定义下载路径
    private String path;
    //指定所下载的文件的保存位置
    private String targetFile;
    //定义下载线程的数量
    private int threadNum;
    //定义下载线程的对象
    private DownloadThread[] threads;
    //下载文件的总大小
    private int fileSize;
    //线程计数器
    private CountDownLatch latch;

    public DownUtil(String path,String targetFile,int threadNum){
        this.path = path;
        this.targetFile = targetFile;
        this.threadNum = threadNum;
        this.latch = new CountDownLatch(threadNum);
        threads = new DownloadThread[threadNum];
    }
    public void downLoad(String referer) throws Exception{
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        //设置请求方法
        conn.setRequestMethod("GET");
        //设置属性
        if (referer!=null){
            Header.set("Referer", referer);
        }
        Header.header.forEach((key, value) -> conn.setRequestProperty(key,value));


        //得到文件大小
        fileSize = conn.getContentLength();
        conn.disconnect();
        int currentPartSize = fileSize / threadNum + 1;
        File directory = new File(PathUtils.getDirectory(targetFile));
        if (!directory.exists()){
            directory.mkdirs();
        }
        RandomAccessFile file = new RandomAccessFile(targetFile,"rw");
        //设置本地文件大小
        file.setLength(fileSize);
        file.close();
        for(int i = 0;i < threadNum;i++){
            //计算每个线程的下载位置
            int startPos = i * currentPartSize;
            //每个线程使用一个RandomAccessFile进行下载
            RandomAccessFile currentPart = new RandomAccessFile(targetFile,"rw");
            //定位该线程的下载位置
            currentPart.seek(startPos);
            //创建下载线程
            threads[i] = new DownloadThread(startPos, currentPartSize, currentPart, path, latch);
            Thread thread = new Thread(threads[i]);
            thread.start();
        }
    }

}